package com.cn.jx.base;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import org.springframework.data.mongodb.core.query.Criteria;

import com.cn.jx.queryTool.ConditionField;
import com.jx.util.Utility;

public abstract class AbstractBase {
	
	protected static Criteria[]  getCriteria(List<ConditionField> filed) {
		ArrayList<Criteria> arrayList = new ArrayList<>();
		filed.forEach(obj->{
			Criteria crit=getCondion(obj);
			arrayList.add(crit);
		});
		return arrayList.toArray(new Criteria[arrayList.size()]);
	}
	

	protected static Criteria getCondion(ConditionField filed) {
		if(filed==null) {
			return null;
		}
		if(Utility.isBlank(filed.getKey())) {
			return null;
		}
		if(filed.getValue()==null) {
			return null;
		}
		switch (filed.getOperator()) {
		case IS:
			return Criteria.where(filed.getKey()).is(filed.getValue());
		case LT:
			return Criteria.where(filed.getKey()).lt(filed.getValue());
		case LTE:
			return Criteria.where(filed.getKey()).lte(filed.getValue());
		case GT:
			return Criteria.where(filed.getKey()).gt(filed.getValue());
		case GTE:
			return Criteria.where(filed.getKey()).gte(filed.getValue());
		case IN:
			return Criteria.where(filed.getKey()).in(filed.getValue());
		case NIN:
			return Criteria.where(filed.getKey()).nin(filed.getValue());
		case AND:
			if(filed.getValue() instanceof String) {
				return Criteria.where(filed.getKey()).and(String.valueOf(filed.getValue()));
			}
		case NUM_NE:
			if(filed.getValue() instanceof Integer) {
				return Criteria.where(filed.getKey()).ne((Integer)filed.getValue());
			}
			break;
		case NE:
			return Criteria.where(filed.getKey()).ne(filed.getValue());
		case ARR_NE:
			Criteria criteria = Criteria.where(filed.getKey()).ne(filed.getValue());
            criteria = Criteria.where(filed.getKey()).elemMatch(criteria);
            return criteria;
		case ALL:
			if(filed.getValue() instanceof ArrayList) {
				return Criteria.where(filed.getKey()).all((ArrayList<?>)filed.getValue());
			}
			break;
		case LIKE:
			Pattern pattern = Pattern.compile("^.*" + filed.getKey() + ".*$", Pattern.CASE_INSENSITIVE);
            return Criteria.where(filed.getKey()).regex(pattern);
		case NUM_IS:
			if(filed.getValue() instanceof Integer) {
				Criteria.where(filed.getKey()).is((Integer)filed.getValue());
			}
			break;
		default:
			break;
		}
		return Criteria.where("1").is("1");
	}
}
